package com.wswy.wyjk.ui.practice.exam

import android.arch.lifecycle.Observer
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.format.DateFormat
import android.text.style.RelativeSizeSpan
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.raft.framework.base.RFBaseFragment
import com.raft.framework.ui.adapter.SampleRecyclerViewAdapter
import com.wswy.wyjk.AppContext
import com.wswy.wyjk.R
import com.wswy.wyjk.model.PracticeType
import com.wswy.wyjk.model.dto.ExamRecord
import com.wswy.wyjk.ui.EXTRA_DATA
import com.wswy.wyjk.ui.common.Router
import com.wswy.wyjk.utils.Tools
import com.wswy.wyjk.utils.gone
import com.wswy.wyjk.utils.loadLayout
import com.wswy.wyjk.utils.visible
import kotlinx.android.synthetic.main.fragment_exam_record.*
import timber.log.Timber

/**
 * 考试记录
 */
class ExamRecordFragment : RFBaseFragment() {

    companion object {
        fun newInstance():RFBaseFragment{


            return ExamRecordFragment()
        }
    }

    private lateinit var examRecordViewModel: ExamRecordViewModel

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_exam_record
    }

    override fun getPageTitle(): String? {
        return AppContext.getContext().getString(R.string.exam_record)
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        examRecordViewModel = provideViewModel(ExamRecordViewModel::class.java)

        arguments?.getParcelable<PracticeType?>(EXTRA_DATA)?.let {
            examRecordViewModel.practiceType = it
        }?:kotlin.run {
            finish()
            return
        }


        examRecordViewModel.getRecordLiveData().observe(this, Observer {

            it?.let {

                if (it.isEmpty()){
                    showEmpty()
                }else{
                    showRecord(it)
                }
            }

        })

        initViews()

    }

    private fun initViews(){

        val toExamClickListener = View.OnClickListener {
            Router.start(it.context,Router.PRACTICE,practiceType = examRecordViewModel.practiceType?.copy()?.apply {
                type = PracticeType.TYPE_EXAM
            })

            finish()

        }

       // tv_empty_to_exam.setOnClickListener(toExamClickListener)

        tv_top_to_exam.setOnClickListener(toExamClickListener)
    }

    private fun showEmpty(){

        layout_content.gone()

      //  layout_empty.visible()
    }

    private fun showRecord(list: List<ExamRecord>){
        layout_content.visible()
      //  layout_empty.gone()

        val context = requireContext()

        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.addItemDecoration(DividerItemDecoration(context,DividerItemDecoration.VERTICAL).apply {
            ContextCompat.getDrawable(context,R.drawable.list_divider_h)?.let {
                setDrawable(it)
            }
        })

        val adapter = RecordAdapter()

        recyclerView.adapter = adapter

        adapter.setNewData(list)
        adapter.notifyDataSetChanged()

        var max = 0
        list.forEach {
            if (it.score > max){
                max = it.score
            }
        }

        tv_record_top.text = getString(R.string.exam_record_top,max)

    }



    class RecordAdapter : SampleRecyclerViewAdapter<ExamRecord,RecordAdapter.RecordViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecordViewHolder {
            return RecordViewHolder(loadLayout(parent,R.layout.item_layout_exam_record))
        }

        override fun onBindViewHolder(holder: RecordViewHolder, position: Int, data: ExamRecord?) {

            data?.run {

                if (isApproved){
                    holder.tvScore.setTextColor(ContextCompat.getColor(AppContext.getContext(),R.color.colorPrimary))
                }else{
                    holder.tvScore.setTextColor(ContextCompat.getColor(AppContext.getContext(),R.color.textColorWrong))
                }

                holder.tvScore.text = SpannableStringBuilder().apply {

                    append(score.toString())

                    append(SpannableString("分").apply {

                        setSpan(RelativeSizeSpan(0.6f), 0, length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)

                    })

                }
                holder.tvUsedTime.text = Tools.formatSecondTime(examTime.toLong())
                holder.tvCreateTime.text = DateFormat.format("yyyy-MM-dd HH:mm",createTime)
            }
        }


        class RecordViewHolder(itemView:View) : RecyclerView.ViewHolder(itemView){

            val tvScore : TextView = itemView.findViewById(R.id.tv_exam_score)
            val tvUsedTime : TextView = itemView.findViewById(R.id.tv_exam_time)
            val tvCreateTime : TextView = itemView.findViewById(R.id.tv_exam_create_time)

        }
    }

}